package com.fangmou.ing.publish.freemarker.directive;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import com.fangmou.ing.publish.freemarker.DirectiveUtils;
import com.fangmou.ing.publish.freemarker.DirectiveBodyWraper;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 区域标出命令
 * @必传参数：name
 * @author kongdy
 */
public class BlockDirective implements TemplateDirectiveModel {

  public void execute(Environment env, Map params, TemplateModel[] loopVars,
      TemplateDirectiveBody body) throws TemplateException, IOException {
    String name = DirectiveUtils.getRequiredParam(params, "name");
    this.registerBlock(name, env, body);
    DirectiveBodyWraper overrideBody = DirectiveUtils.getOverrideBody(env, name);
    if (overrideBody == null) {
      if (body != null) {
        body.render(env.getOut());
      }
    } else {
      DirectiveUtils.setTopBodyForParentBody(env, new DirectiveBodyWraper(body, env), overrideBody);
      overrideBody.render(env.getOut());
    }
  }
  
  /**
   * 注册block到模板解析环境，以便后续调用
   * @param name
   * @param env
   * @param body
   * @throws TemplateException
   * @throws IOException
   */
  private void registerBlock(String name, Environment env, TemplateDirectiveBody body) throws TemplateException, IOException{
    StringWriter sout = new StringWriter();
    body.render(sout);
    env.getConfiguration().setCustomAttribute(DirectiveUtils.getOverrideVariableName(name), sout.toString());
  }

}
